//
//  KFDNewPostViewController.m
//  
//
//  Created by JIRENTIANXIANG on 6/28/15.
//
//

#import "KFDNewPostViewController.h"
#import "DoImagePickerController.h"
#import "ui_config.h"
#import "KFDInvestmentCommunityManager.h"
#import "JTToast.h"
#import <WUEmoticonsKeyboard/WUEmoticonsKeyboard.h>
#import "JTPictureSelectionView.h"

@interface KFDNewPostViewController ()<DoImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (strong, nonatomic) JTPictureSelectionView *pictureSelectionView;
@property (weak, nonatomic) IBOutlet UITextView *contentView;
@property (strong,nonatomic) WUEmoticonsKeyboard* keyboard;
@property (weak, nonatomic) IBOutlet UIButton *emoticonButton;

@end

@implementation KFDNewPostViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.uiConfigurator configureNavigationBarWithBackAction:@selector(goBack)];
    self.title=@"发布心得";
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(publishButtonPressed)];
    self.keyboard=[WUEmoticonsKeyboard keyboard];
    self.keyboard.backgroundColor=[UIColor whiteColor];
    NSMutableArray* items=[NSMutableArray array];
    for (int i=0; i<40; i++) {
        WUEmoticonsKeyboardKeyItem* item=[[WUEmoticonsKeyboardKeyItem alloc] init];
        item.image=[UIImage imageNamed:[NSString stringWithFormat:@"[face-%d].png",i+100]];
        item.textToInput=[NSString stringWithFormat:@"[face:%d]",i+100];
        [items addObject:item];
    }
    WUEmoticonsKeyboardKeyItemGroup* itemGroup0=[[WUEmoticonsKeyboardKeyItemGroup alloc] init];
    itemGroup0.keyItems=items;
    self.keyboard.keyItemGroups=@[itemGroup0];
    self.emoticonButton.selected=NO;
//    self.pictures=[[NSMutableArray alloc] init];
    [self setupPictureSelectionView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(imageSizeExceedLimit) name:KFDImageSizeExceedLimitNotification object:nil];
}

-(void)imageSizeExceedLimit
{
    [[JTToast makeText:@"图片大小超过限制"] showInView:self.view size:CGSizeMake(160, 40)];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KFDImageSizeExceedLimitNotification object:nil];
}

-(void)setupPictureSelectionView
{
    self.pictureSelectionView=[[JTPictureSelectionView alloc] initWithFrame:CGRectMake(0, 236, SCREEN_WIDTH, 118)];
    self.pictureSelectionView.userInteractionEnabled=YES;
    JTPictureSelectionViewConfiguration* config=[[JTPictureSelectionViewConfiguration alloc] init];
    config.numberOfColumns=3;
    config.margin=16;
    config.gap=8;
    self.pictureSelectionView.config=config;
    [self.view addSubview:self.pictureSelectionView];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.contentView becomeFirstResponder];
}

- (IBAction)emoticonButtonPressed:(UIButton*)sender {
    sender.selected=!sender.isSelected;
    if (sender.isSelected) {
        [self.contentView switchToEmoticonsKeyboard:self.keyboard];
        [sender setImage:[UIImage imageNamed:@"keyboard.jpg"] forState:UIControlStateNormal];
    }else{
        [self.contentView switchToDefaultKeyboard];
        [sender setImage:[UIImage imageNamed:@"face-ico"] forState:UIControlStateNormal];
    }
}

- (IBAction)pickImage:(id)sender {
    NSUInteger maxCount=6-self.pictureSelectionView.subviews.count;
    if (maxCount>0) {
        UIAlertController* alertController=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction* chooseFromAlbum=[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            DoImagePickerController* imagePickerController=[[DoImagePickerController alloc] init];
            imagePickerController.nResultType=DO_PICKER_RESULT_UIIMAGE;
            imagePickerController.nColumnCount=3;
            imagePickerController.nMaxCount=maxCount;
            imagePickerController.delegate=self;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }];
        [alertController addAction:chooseFromAlbum];
        UIAlertAction* takePhoto=[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            UIImagePickerController* imagePicker=[[UIImagePickerController alloc] init];
            imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
            imagePicker.delegate=self;
            [self presentViewController:imagePicker animated:YES completion:nil];
        }];
        [alertController addAction:takePhoto];
        UIAlertAction* cancel=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
        }];
        [alertController addAction:cancel];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

-(void)publishButtonPressed
{
    KFDInvestmentCommunityManager* manager=[KFDInvestmentCommunityManager sharedManager];
    NSString* content=self.contentView.text;
    if ([manager checkContent:content illegalInputHandler:^(NSString *message) {
        [[JTToast makeText:message] showInView:self.view size:CGSizeMake(20*message.length, 40)];
    }]) {
        if (self.pictureSelectionView.pictures&&self.pictureSelectionView.pictures.count>0) {
            __block NSUInteger count=self.pictureSelectionView.pictures.count;
            NSMutableArray* pictureIds=[NSMutableArray array];
            for (UIImage* picture in self.pictureSelectionView.pictures) {
                [manager uploadPicture:picture successHandler:^(NSString *pictureId) {
                    count--;
                    if (pictureId) {
                        [pictureIds addObject:pictureId];
                    }
                    if (count==0) {
                        [self publishPostWithContent:content pictures:pictureIds];
                    }
                } failureHandler:^(KFDResponseBody *response) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[JTToast makeText:response.message] showInView:self.view size:CGSizeMake(response.message.length*20, 40)];
                    });
                }];
            }
            
        }else{
            [self publishPostWithContent:content pictures:nil];
        }
    }
}

-(void)publishPostWithContent:(NSString*)content pictures:(NSArray*)pictures
{
    KFDInvestmentCommunityManager* manager=[KFDInvestmentCommunityManager sharedManager];
    [manager publishPostWithContent:content pictures:pictures successHandler:^(NSString *postId) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[JTToast makeText:@"发布成功"] showInView:self.view size:CGSizeMake(80, 40)];
            [self goBack];
        });
    } failureHandler:^(KFDResponseBody *response) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[JTToast makeText:response.message] showInView:self.view size:CGSizeMake(response.message.length*20, 40)];
        });
    }];
}

-(void)goBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

//---------------------------------------------------------------------------------
#pragma mark - DoImagePickerControllerDelegate
//---------------------------------------------------------------------------------
- (void)didCancelDoImagePickerController
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didSelectPhotosFromDoImagePickerController:(DoImagePickerController *)picker result:(NSArray *)aSelected
{
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.pictureSelectionView addPictures:aSelected];
}
//---------------------------------------------------------------------------------

//---------------------------------------------------------------------------------
#pragma mark - UIImagePickerController
//---------------------------------------------------------------------------------
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage* image=info[@"UIImagePickerControllerOriginalImage"];
//    [self addPicture:image];
    [self.pictureSelectionView addPicture:image];
    
}
//---------------------------------------------------------------------------------

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
